package error;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.HtmlCreator;
import util.TextUtils;

/**
 * 通用错误处理器 Servlet implementation class ErrorHandler
 */
//@WebServlet("/ErrorHandler")
public class ErrorHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ErrorHandler() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 这些通过反射的方式获取到的，具体可以参考。。http://www.runoob.com/servlet/servlet-exception-handling.html
		Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
		String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
		String errorMsg = (String) request.getAttribute("javax.servlet.error.message");

		if (TextUtils.isEmpty(servletName)) {
			servletName = "Unknown";
		}

		if (TextUtils.isEmpty(requestUri)) {
			requestUri = "Unknown";
		}

		StringBuffer webContent = new StringBuffer("<h1>异常信息处理</h1>\n");
		PrintWriter writer = response.getWriter();
		if (throwable==null&&statusCode==null) {
			webContent.append("</br><h2>错误信息丢失</h2></br>");
			webContent.append("请返回<a href=\""+response.encodeURL("https://localhost:6060/")+"\">主页</a>");
		}else if (statusCode!=null) {
			webContent.append("错误代码："+statusCode);
		}else {
			webContent.append("<h2>错误信息</h2></br>");
			webContent.append("ServletName："+servletName+"</br></br>");
			webContent.append("异常类型："+throwable.getClass().getName()+"</br></br>");
			webContent.append("请求的URL："+requestUri+"</br></br>");
			webContent.append("异常信息："+throwable.getMessage());
		}
		writer.print(HtmlCreator.createWebContent("异常信息处理", webContent.toString()));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
